package com.bookRecommend.provider;

import com.bookRecommend.model.Score;
import org.apache.ibatis.builder.annotation.ProviderMethodResolver;
import org.apache.ibatis.jdbc.SQL;

public class ScoreProvider implements ProviderMethodResolver {
    //score对象
    public String selectByScore(Score score) {
        SQL sql = new SQL().SELECT("score");
        String type = "select";
        return getSql(sql,score,type);
    }

    public String insertScore(Score score){
        SQL sql = new SQL().INSERT_INTO("score");
        String type = "insert";
        return getSql(sql,score,type);
    }

    public String updateScore(Score score){
        SQL sql = new SQL().UPDATE("score");
        String type = "update";
        return getSql(sql,score,type);
    }

    public String deleteScore(Score score){
        SQL sql = new SQL().DELETE_FROM("score");
        String type = "delete";
        return getSql(sql,score,type);
    }

    private String getSql(SQL sql, Score score, String type) {
        if (score != null) {
            if (score.getId() != null) {
                switch (type) {
                    case "select" -> sql.WHERE("id like '${id}'");
                    case "update", "delete" -> sql.WHERE("id = #{id}");
                    case "insert" -> sql.VALUES("id", "#{id}");
                }
            }
            if (score.getUserId() != null) {
                switch (type) {
                    case "select" -> sql.WHERE("userid like '${userId}'");
                    case "update" -> sql.SET("userid = #{userId}");
                    case "delete" -> sql.WHERE("userid = #{userId}");
                    case "insert" -> sql.VALUES("userid", "#{userId}");
                }
            }
            if (score.getBookId() != null) {
                switch (type) {
                    case "select" -> sql.WHERE("bookid like '${bookId}'");
                    case "update" -> sql.SET("bookid = #{bookId}");
                    case "delete" -> sql.WHERE("bookid = #{bookId}");
                    case "insert" -> sql.VALUES("bookid", "#{bookId}");
                }
            }
            if (score.getScore() != null) {
                switch (type) {
                    case "select" -> sql.WHERE("score like '${score}'");
                    case "update" -> sql.SET("score = #{score}");
                    case "delete" -> sql.WHERE("score = #{score}");
                    case "insert" -> sql.VALUES("score", "#{score}");
                }
            }
        }
        return sql.toString();
    }
}